package com.ksyzt.ksite2.server.common;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import com.ksyzt.gwt.server.common.Util;

public class TemplateHelper {

	/**
	 * 更具properties中的信息替换文件，并返回文本内容
	 *
	 * @param filepath
	 * @param properties
	 * @return
	 */
	public static String ReplaceTemplate(String filepath, Properties pros) {

		StringBuilder sb;
		try {
			sb = Util.readFromFile(new File(filepath));

		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}

		String temp = sb.toString();

		Enumeration<Object> keys = pros.keys();

		while (keys.hasMoreElements()) {
			String key = keys.nextElement().toString();
			String value = pros.getProperty(key);

			temp = temp.replaceAll(key, value);
		}

		return temp;
	}

	/**
	 * 模板替换函数，并直接写入文件
	 *
	 * @param bottomTemplate
	 * @param pros
	 * @param bottomJsp
	 * @return
	 */
	public static String ReplaceTemplate(String template, Properties pros,
			String target) {
		String res = "";
		File input = new File(template);
		if (input.exists() == false) {
			res = "没有找到模板文件" + template;
		} else {
			String content = "";
			try {
				content = Util.readTextFile(input);
			} catch (IOException e) {
				e.printStackTrace();
				return e.getMessage();
			}

			Enumeration<Object> keys = pros.keys();

			while (keys.hasMoreElements()) {
				String key = keys.nextElement().toString();
				String value = pros.getProperty(key);

				content = content.replaceAll(key, value);
			}

			Util.WriteStringToFile(target, content);
			res = "OK";
		}
		return res;
	}
}
